package net.result;

import com.opensymphony.xwork2.ActionInvocation;
import net.base.ToolsAction;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

public class JsonResult extends BaseResult {
    protected boolean isAjax = true;

    protected void doExecute(String arg0, ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
       this.execute(invocation);

    }
    public void execute(ActionInvocation invocation) throws Exception {
        ServletContext sc = ServletActionContext.getServletContext();
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/json");

        PrintWriter output = response.getWriter();
        ToolsAction baseAction = (ToolsAction) invocation.getAction();

        output.flush();
        try {

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
            jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));

            JSONObject js = JSONObject.fromObject(baseAction.getModel(), jsonConfig);
            js.put("code", new Integer(baseAction.getCode()));
            js.put("msg", baseAction.getMsg());
            js.put("expMsg", baseAction.getExpMsg());
            js.write(output);
            System.out.println(this.getClass() + "->" + js.toString());
        } catch (Exception ex) {
            HashMap hashMap = new HashMap();
            hashMap.put("code", "-1");
            hashMap.put("type", "err");
            hashMap.put("msg", "发生错误");
            hashMap.put("mx", ex.getMessage());


            JSONObject js = new JSONObject();
            js.put("msg", hashMap);
            output.write(js.toString());
        } finally {
            if (output != null) output.close();
        }
    }

}
